package com.proactive.webapp.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.proactive.webapp.dao.MemberDAO;
import com.proactive.webapp.dao.MenuDAO;
import com.proactive.webapp.dao.ResourceCategoryDAO;
import com.proactive.webapp.dao.ResourceDAO;
import com.proactive.webapp.entity.Member;
import com.proactive.webapp.entity.Menu;
import com.proactive.webapp.entity.Resource;
import com.proactive.webapp.entity.ResourceCategory;
import com.proactive.webapp.util.AwsUtil;
import com.proactive.webapp.util.CompressImage;
import com.proactive.webapp.util.DateConversion;
import com.proactive.webapp.util.FileUtil;
import com.proactive.webapp.util.MenuUtil;
import com.proactive.webapp.util.PageCount;

@Controller
public class MemberResourceController {
	ApplicationContext context =  new ClassPathXmlApplicationContext("spring-module.xml");
	
	@RequestMapping(value = "/addResourceCont", method = RequestMethod.GET)
	public ModelAndView addResourceCont(HttpSession session) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			model.setViewName("addResource");
			List<ResourceCategory> category1List = new ArrayList<ResourceCategory>();
			ResourceCategoryDAO resourceCategoryDAO = (ResourceCategoryDAO) context.getBean("resourceCategoryDAO");
			category1List = resourceCategoryDAO.getList();
			List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
			model.addObject("menuList", menuList);
			model.addObject("category1", category1List);
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/addResource", method = RequestMethod.POST)
	public ModelAndView addResource(@ModelAttribute Resource resource, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			String path = session.getServletContext().getRealPath("resources/image/resource");
			DateConversion dateConversion = new DateConversion();
			Date now = new Date();
			resource.setAccount(loginMember.getAccount());
			
			//new AWS
			AwsUtil awsUtil = new AwsUtil();
	        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
	        awsUtil.getInstance();

			//upload image
			if(resource.getImage().getSize() > 0){
				FileUtil fileUtil = new FileUtil(resource.getImage().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
				
	        	//rename and move
				File targetFile = new File(path, newFileName);
		        if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	resource.getImage().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        
				//compress image
				if(!fileUtil.getFileType().equals("gif")){
		    		CompressImage compressImage = new CompressImage();
		        	compressImage.compress(path+"/", newFileName, 0, 0, false);
		        }
				
				//upload file AWS
				try {		        	
					awsUtil.uploadFile("resources/image/resource/", targetFile);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        //delete local file
		        targetFile.delete();	
				resource.setImagePath("resources/image/resource/"+newFileName);
			}
			
			
			ResourceDAO resourceDAO = (ResourceDAO)context.getBean("resourceDAO");
			resource.setContent(StringEscapeUtils.escapeHtml(resource.getContent()));
			int resourceID = resourceDAO.insert(resource);
			
			model.setViewName("redirect:/resource");
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}
	
	@RequestMapping(value = "/memberResource", method = RequestMethod.GET)
	public ModelAndView getMemberResourceList(HttpServletRequest request, HttpSession session) {
		ModelAndView model = new ModelAndView();
		Member loginMember = (Member)session.getAttribute("loginMember");
		if (request.getParameter("id") != null) {
			MemberDAO memberDAO = (MemberDAO) context.getBean("memberDAO");
			ResourceDAO resourceDAO = (ResourceDAO) context.getBean("resourceDAO");
			Member member = new Member();			
			List<Resource> resourceList = new ArrayList<Resource>();
			
			String loginAccount = loginMember==null?"":loginMember.getAccount();
			
			String memberNO = request.getParameter("id");
			int pageNow = request.getParameter("p")==null?1:Integer.parseInt(request.getParameter("p"));
			
			member.setMemberNO(memberNO);
			member = memberDAO.getByMemberNO(member);//用memberNO取得memberAccount
			if(member.getAccount()!=null){
				
				if(loginMember != null)
					member = memberDAO.getByLogin(member, loginMember.getAccount());//取得member資料
				int count = 0;
				if(member.isMyselfFlag())
					count = resourceDAO.countTotalByWriter(loginAccount);
				else
					count = resourceDAO.countTotalByMember(loginAccount);
				
				//set pager
				int pageSize = 12;
				String pageUrl = "memberResource";
				String pageEndUrl1 = "&id="+memberNO;
				PageCount pageCount = new PageCount(pageNow, pageSize, count, pageUrl, pageEndUrl1);
				pageCount.calculate();
				if(member.isMyselfFlag())
					resourceList = resourceDAO.getListByWriter(loginAccount, pageCount.getStart(), pageSize);
				else
					resourceList = resourceDAO.getListByMember(member.getAccount(), loginAccount, pageCount.getStart(), pageSize);
				
				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				
				//set model
				model.addObject("page", pageCount);
				model.addObject("member", member);
				model.addObject("resourceList", resourceList);
				model.addObject("menuList", menuList);
				model.setViewName(loginMember!=null?"memberResource1":"memberResource2");
			
			}
			else
				model.setViewName("redirect:/");
			
		} 
		else
			model.setViewName(loginMember!=null?"redirect:/memberResource?id="+loginMember.getMemberNO():"redirect:/login");

		
		return model;
	}
	
	@RequestMapping(value = "/actResource", method = RequestMethod.POST)
	public ModelAndView actResource(int id, String act, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){//檢查登入
			ResourceDAO resourceDAO = (ResourceDAO) context.getBean("resourceDAO");
			Resource resource = new Resource();
			resource.setId(id);
			resource = resourceDAO.get(resource);
			if(resource.getAccount().equals(loginMember.getAccount())){//檢查是否為作者
				if(act.equals("delete")){//delete resource
					//new AWS
					AwsUtil awsUtil = new AwsUtil();
			        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
			        awsUtil.getInstance();		      
			        //delete image
					if(!resource.getImagePath().equals("")){
						awsUtil.deleteFile(resource.getImagePath());
					}
					resource.setStatus(3);
					
				}
				else if(act.equals("show")){//show resource
					resource.setStatus(1);
				}
				else if(act.equals("hide")){//hide resource
					resource.setStatus(2);
				}
				resourceDAO.updateStatus(resource);
				model.setViewName("redirect:"+request.getHeader("referer"));
			}
			else 
				model.setViewName("redirect:/memberResource");
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	@RequestMapping(value = "/modiResourceCont", method = RequestMethod.GET)
	public ModelAndView modiResourceCont(HttpSession session, int id) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			ResourceDAO resourceDAO = (ResourceDAO) context.getBean("resourceDAO");
			Resource resource = new Resource();
			resource.setId(id);
			resource = resourceDAO.get(resource);
			if(resource.getAccount().equals(loginMember.getAccount())){
				model.setViewName("modiResource");
				List<ResourceCategory> category1List = new ArrayList<ResourceCategory>();
				ResourceCategoryDAO resourceCategoryDAO = (ResourceCategoryDAO) context.getBean("resourceCategoryDAO");
				category1List = resourceCategoryDAO.getList();
				for(int j=0; j<category1List.size(); j++){
					if(category1List.get(j).getId() == resource.getCategoryID())
						category1List.get(j).setClassString("selected");
				}
				

				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				model.addObject("menuList", menuList);
				model.addObject("category1", category1List);
				model.addObject("resource", resource);
			}
			else
				model.setViewName("redirect:/resource");
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/modiResource", method = RequestMethod.POST)
	public ModelAndView modiResource(@ModelAttribute Resource resource, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			ResourceDAO resourceDAO = (ResourceDAO)context.getBean("resourceDAO");
			Resource oldResource = new Resource();
			oldResource.setId(resource.getId());
			oldResource = resourceDAO.get(oldResource);
			if(oldResource.getAccount().equals(loginMember.getAccount())){
				//new AWS
				AwsUtil awsUtil = new AwsUtil();
		        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
		        awsUtil.getInstance();
		        
				String path = session.getServletContext().getRealPath("/");
				String path1 = session.getServletContext().getRealPath("resources/image/resource");
				DateConversion dateConversion = new DateConversion();
				Date now = new Date();
				resource.setAccount(loginMember.getAccount());
				
				//upload image
				if(resource.getImage().getSize() > 0){
					FileUtil fileUtil = new FileUtil(resource.getImage().getOriginalFilename());
					String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
					
					//rename and move
					File targetFile = new File(path1, newFileName);
			        if(!targetFile.exists()){
			            targetFile.mkdirs();
			        }
			        try {
			        	resource.getImage().transferTo(targetFile);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
			        
		        	//delete original file
			        if(!oldResource.getImagePath().equals("")){
			        	awsUtil.deleteFile(oldResource.getImagePath());
			        }
			        	
			        //compress image
					if(!fileUtil.getFileType().equals("gif")){
			    		CompressImage compressImage = new CompressImage();
			        	compressImage.compress(path1+"/", newFileName, 0, 0, false);
			        }
					
					//upload file AWS
			        try {
						awsUtil.uploadFile("resources/image/resource/", targetFile);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        
			        //delete local file
			        targetFile.delete();	
		        	resource.setImagePath("resources/image/resource/"+newFileName);
				}
				else
		        	resource.setImagePath(oldResource.getImagePath());							

				resource.setContent(StringEscapeUtils.escapeHtml(resource.getContent()));
				resourceDAO.update(resource);

				
			}
			model.setViewName("redirect:/memberResource?id="+loginMember.getMemberNO());
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
}
